package com.huluobo.day11_im.addGroup.presenter;

import android.util.Log;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroupInfo;
import com.hyphenate.chat.EMGroupOptions;
import com.hyphenate.exceptions.HyphenateException;

import java.util.List;

public class AddGroupPresenter implements AddGroupContract.Presenter {
    private AddGroupContract.View view;

    public AddGroupPresenter(AddGroupContract.View view) {
        this.view = view;
    }

    @Override
    public void createGroup(String groupName, String desc, String[] users, String reason,
                            EMGroupOptions emGroupOptions) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().groupManager().createGroup(groupName, desc, users,
                            reason,
                            emGroupOptions);
                    view.onCreateGroupSuccess();
                } catch (HyphenateException e) {
                    view.onCreateGroupFailed(e.getMessage());
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    @Override
    public void findAllGroups(int pageSize, String cursor) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    List<EMGroupInfo> groupsList =
                            EMClient.getInstance().groupManager().getPublicGroupsFromServer(pageSize,
                                    cursor).getData();
                    view.onFindAllGroupsSuccess(groupsList);
                } catch (HyphenateException e) {
                    view.onFindAllGroupsFailed(e.getMessage());
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    @Override
    public void joinGroup(String groupId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().groupManager().joinGroup(groupId);
                    view.onJoinGroupSuccess();
                } catch (HyphenateException e) {
                    if (e.getErrorCode() == 601) {
                        view.onJoinGroupFailed("601");
                        return;
                    }
                    view.onJoinGroupFailed(e.getMessage());
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
}
